import axios from 'axios'
import vue from '../main.js'

axios.defaults.baseURL = process.env.API_ROOT + '/api'

// 创建axios实例
const service = axios

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    config.headers = {
      'ba-user-token': JSON.parse(localStorage.getItem('userInfo')) ? JSON.parse(localStorage.getItem('userInfo')).token : '', // 用户token
      'lang': localStorage.getItem('lang') || 'cn',
      server: 'true',
      ...config.headers
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  res => {
    if (res.status == 200) {
      if (res.data.code === 0) {
        vue.$toast.fail(res.data.msg)
        return res.data
      } else if (res.data.code === 1) {
        if (res.data.msg !== 'success') {
          vue.$toast.success(res.data.msg)
        }
        return res.data
      } else if (res.data.code === 302 || res.data.code === 409) {
        vue.$toast.fail(res.data.msg)
        localStorage.removeItem('userInfo')
        vue.$router.push('/signIn')
      }
    } else {
      vue.$toast.fail(vue.$t('info.info0'))
      console.error(res.config.url)
    }
  },
  error => {
    vue.$toast.fail(vue.$t('info.info0'))
    return error.response
  }
)

export default service
